package com.xinyue.game.gateway.common;

import io.netty.buffer.ByteBuf;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;

import java.nio.charset.StandardCharsets;

/**
 * @author 王广帅
 * @since 2023/7/25 21:34
 **/
@Data
public class GameGatewayMessageResponseHeader {
    private String userKey;

    @Setter(AccessLevel.NONE)
    private byte[] userKeyBytes;
    private String requestUri;
    @Setter(AccessLevel.NONE)
    private byte[] requestUriBytes;
    private long responseTime;
    private String requestId;
    @Setter(AccessLevel.NONE)
    private byte[] requestIdBytes;

    private int messageType;
    private int errorCode;
    private String errorMsg;
    @Setter(AccessLevel.NONE)
    private byte[] errorMsgBytes;

    public int getHeaderSize() {
        this.requestUriBytes = this.requestUri.getBytes(StandardCharsets.UTF_8);
        this.requestIdBytes = this.requestId.getBytes(StandardCharsets.UTF_8);
        this.userKeyBytes = this.userKey.getBytes(StandardCharsets.UTF_8);
        int size = 13 + 2 + this.userKeyBytes.length + this.requestIdBytes.length + 2 + this.requestUriBytes.length;
        if (errorMsg != null) {
            this.errorMsgBytes = this.errorMsg.getBytes(StandardCharsets.UTF_8);
            size += this.errorMsgBytes.length;
        }
        return size;
    }

    public void write(ByteBuf byteBuf) {
        byteBuf.writeShort(this.userKeyBytes.length);
        byteBuf.writeBytes(this.userKeyBytes);

        byteBuf.writeBytes(this.requestIdBytes);

        byteBuf.writeShort(this.requestUri.length());
        byteBuf.writeBytes(this.requestUriBytes);

        byteBuf.writeByte(this.messageType);

        byteBuf.writeLong(this.responseTime);

        byteBuf.writeInt(this.errorCode);
        if (this.errorMsgBytes != null) {
            byteBuf.writeBytes(this.errorMsgBytes);
        }
    }

    public String toString() {
        StringBuilder str = new StringBuilder();
        str.append("requestId: ").append(this.requestId)
                .append(", requestUri: ").append(this.requestUri)
                .append(", userKey: ").append(this.userKey)
                .append(", responseTime: ").append(this.responseTime)
                .append(", errorCode: ").append(this.errorCode)
                .append(", errorMsg: ").append(this.errorMsg);
        return str.toString();
    }
}
